/**
* @note 衣带渐宽终不悔,Bug寻得人憔悴
* @author yuliang
* @description 车辆详情
* @createDate 2020/8/25
*
*/

import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Text,
  SafeAreaView,
  Image,
  TouchableOpacity,
  Modal,
  ScrollView,
  PixelRatio,
  TextInput,
  NativeModules,
  Keyboard
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import {
  isAndroid,
  mainBgColorLightGray,
  fontColorSecDeepGray,
  fontColorBlack,
  screenWidth,
  screenHeight,
  splitLineColorLightGray,
  mainBgColorWhite,
  fontColorCoffee,
  px2dp
} from '@/styles';
import {
  Button,
  msg,
  XMHeader,
  BackImageOn
} from '@/common';
import { checkMobile } from '@/common/util';
import supply from '@/api/supply';
import contract from '@/api/contract';
import { carAvatar, carOwner, driver } from '@/images';

import CarInfoCell from './components/car-info-cell';
import DriverCell from './components/driver-cell';

const { Submit } = Button;

export default class OwnerCarDetail extends Component {
  constructor(props) {
    super(props);
    const { navigation } = props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { data } = params;
    this.state = {
      carDetails: {},
      routerFrom: '',
      setDriverIsShow: false,
      driverPhone: '',
      isShowInput: true,
      data,
      isHasCarInfo: true,
      // 车辆id
      carId: '',
      keyboardHeight: '',
      carNo: '', // 车牌号
      contractUrl: '', // 合同url
    };
  }

  _keyboardDidShow(e) {
    this.setState({
      keyboardHeight: e.startCoordinates.height,
    });
  }

  _keyboardDidHide(e) {
    this.setState({
      keyboardHeight: 0,
    });
  }

  componentDidMount() {
    this.keyboardDidShowListener = Keyboard.addListener(
      'keyboardWillShow',
      this._keyboardDidShow.bind(this),
    );
    this.keyboardDidHideListener = Keyboard.addListener(
      'keyboardWillHide',
      this._keyboardDidHide.bind(this),
    );
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { data } = params;
    this.initData(data);
  }

  // 入口接口调取信息
  initData = (data) => {
    supply.getCarinfo({ id: data.id }).then(res => {
      if (res.success) {
        const resData = res.data;
        this.setState({ carDetails: resData });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  }

  // 设置司机
  submit = () => {
    this.onChangeModal({ type: 'setDriverIsShow', val: true });
  }

  onChangeModal = ({ type, val }) => {
    this.setState({ [type]: val, isShowInput: true });
  }

  // 车主端设置司机按钮
  btn = (index) => {
    if (this.state.routerFrom == 'CarOwnerTruckList' && index == 5) {
      return (<TouchableOpacity
        activeOpacity={1}
        style={{ marginRight: px2dp(32) * 2 }}
        onPress={() => {
        }}
      >
        <Submit
          text='设置司机'
          btnTextStyle={{
            color: '#BA914A',
            fontSize: px2dp(14) * 2
          }}
          boxStyle={{
            width: px2dp(80) * 2,
            height: px2dp(28) * 2,
            backgroundColor: 'tranparent',
            borderColor: '#BA914A',
            borderWidth: px2dp(2),
            borderRadius: px2dp(4) * 2,
          }}
          disabled={false}
          onClick={() => {
            this.submit();
          }}
        />
      </TouchableOpacity>);
    }
    if (this.state.routerFrom == 'CarOwnerTruckList' && index == 3) {
      return (<TouchableOpacity
        activeOpacity={1}
        style={{ marginRight: px2dp(32) * 2 }}
        onPress={() => {
          this.previewContract();
        }}
      >
        <Text style={{ fontSize: px2dp(28), color: fontColorCoffee }}>查看合同&gt;</Text>
      </TouchableOpacity>);
    }
  }

  // 删除车辆
  delCar = () => {
    NativeModules.WindowModule.showWindow(
      {
        content: '确定要删除该车辆吗？',
      },
      (e) => {
        if (e == 1) {
          supply.deleteCar({
            carId: this.state.carId
          }).then(res => {
            if (res.success) {
              msg.emit('app:tip', { text: '操作成功' });
              msg.emit('router: refreshRoute', {
                routeName: this.state.routerFrom,
              });
              msg.emit('router: goToNext', { routeName: this.state.routerFrom });
            } else {
              msg.emit('app:tip', { text: '网络异常' });
            }
          }).catch(err => {
            msg.emit('app:tip', { text: '网络异常' });
          });
        }
      },
    );
  }

  // 设置司机（自己/别人）
  toSetDriver = (type) => {
    if (type == '别人') {
      this.setState({
        isShowInput: false
      });
    } else if (type == '提交') {
      if (checkMobile(this.state.driverPhone)) {
        this.setDriverApi(2, this.state.driverPhone);
      } else {
        msg.emit('app:tip', { text: '请正确填写司机手机号码' });
      }
    } else if (type == '自己') {
      this.setDriverApi(1, '');
    }
  }

  // 设置司机接口调取
  setDriverApi = (type, mobile) => {
    const { routerFrom, carId } = this.state;
    let params = {
      carId: carId,
      type,
      mobile
    };
    supply.setDriver(params).then(res => {
      if (res.success) {
        msg.emit('app:tip', { text: '设置成功' });
        this.onChangeModal({ type: 'setDriverIsShow', val: false });
        this.initData(routerFrom, carId);
      } else {
        msg.emit('app:tip', { text: res.msg });
        this.onChangeModal({ type: 'setDriverIsShow', val: false });
      }
    }).catch(err => {
      msg.emit('app:tip', { text: '网络异常' });
      this.onChangeModal({ type: 'setDriverIsShow', val: false });
    });
  }

  // 添加车辆
  addCar = () => {
    msg.emit('router: goToNext', {
      routeName: 'CarOwnerTruckList',
      routerFrom: 'CarDetail'
    });
  }

  render() {
    const {
      driverPhone,
      isShowInput,
      data,
      routerFrom,
      isHasCarInfo,
      carDetails
    } = this.state;
    const listData = [
      {
        url: carOwner,
        title: '我自己',
        text: '设定我自己为司机',
        type: '自己' },
      {
        url: driver,
        title: '别人',
        text: '设定别人为司机',
        type: '别人'
      },
    ];
    const obdStatus = () => {
      if (carDetails) {
        return carDetails.obdStatus == 1 ? '在线' : `离线${carDetails.obdInfo ? carDetails.obdInfo : ''}`;
      }
      return '';
    };
    return (
      <SafeAreaView style={styles.container}>
        <XMHeader
          title='车辆详情'
          renderLeft={() => {
            return (
              <BackImageOn onClick={() => {
                msg.emit('router: back');
              }}
              />
            );
          }}
          renderRight={() => {
          }}
        />
        <ScrollView>
          <View style={styles.header}>
            <View style={styles.headLeft}>
              <Image
                resizeMode='contain'
                style={styles.headImg}
                source={carAvatar}
              />
            </View>
            <View style={styles.headRight}>
              <View style={styles.byContainer}>
                <Text style={styles.fontSize16}>
                  {carDetails && carDetails.carNo}
                </Text>
                {
                  data.state == '2' &&
                  <View style={styles.byBox}>
                    <Text style={styles.byText}>维修保养中</Text>
                  </View>
                }
              </View>
              <Text style={styles.fontSize12}>
                {carDetails && carDetails.createTime}
                {' '}
                入驻
              </Text>
            </View>
          </View>
          <View style={styles.innerBox}>
            <CarInfoCell
              label='车龄'
              value={carDetails && carDetails.age ? `${carDetails.age}年` : '-'}
            />
            <CarInfoCell
              label='车型'
              value={carDetails && carDetails.carType}
            />
            <CarInfoCell
              label='车长'
              value={`${carDetails && carDetails.vehicleLength || ''}`}
            />
            <CarInfoCell
              label='载重'
              value={carDetails && carDetails.vehicleTonnage ? `${carDetails.vehicleTonnage}吨` : '-'}
              isBorder={false}
            />
          </View>
          <View style={styles.innerBox}>
            <CarInfoCell
              label='所属企业'
              value={carDetails && carDetails.legalName}
            />
            <CarInfoCell
              label='合作类型'
              value={carDetails && carDetails.vehicleCoopType}
              isCheckContract
              checkContract={this.checkContract}
            />
            {
              carDetails.obdStatus &&
              <CarInfoCell
                label='OBD设备'
                value={obdStatus()}
              />
            }
            <CarInfoCell
              label='车载设备'
              value=''
              isBorder={false}
            />

          </View>
          <View style={styles.innerBox}>
            <DriverCell
              label='主驾驶'
              submitDriver={() => this.submitDriver('主', carDetails.ownerDriverName)}
              value={carDetails && carDetails.ownerDriverName ? `${carDetails && carDetails.ownerDriverName || ''}  ${carDetails.ownerDriverMobile || ''}` : '暂无司机'}
              isDriverBan={carDetails && carDetails.ownerDriverName ? (carDetails.ownerDriverStatus == 3) : false}
            />
            <DriverCell
              label='副驾驶'
              submitDriver={() => this.submitDriver('副', carDetails.secondDriverName)}
              value={carDetails && carDetails.secondDriverName ? `${carDetails && carDetails.secondDriverName || ''}  ${carDetails.secondDrivermobile || ''}` : '暂无司机'}
              isDriverBan={carDetails && carDetails.secondDriverName ? (carDetails.secondDriverName == 3) : false}
              isBorder={false}
            />

          </View>
        </ScrollView>

        <Modal
          animationType='slide'
          transparent
          visible={this.state.setDriverIsShow}
          onRequestClose={() => {
            this.onChangeModal({ type: 'setDriverIsShow', val: false });
          }}
          onShow={() => { }}
        >

          {/* 点击遮罩层关闭 */}
          <TouchableOpacity
            style={styles.mask}
            onPress={() => {
              this.onChangeModal({ type: 'setDriverIsShow', val: false });
            }}
          />
          <View style={[
            styles.infoContainer,
            { marginBottom: Number(this.state.keyboardHeight) }
          ]}
          >
            <View style={styles.headers}>
              <TouchableOpacity
                style={styles.cancel}
                onPress={() => {
                  this.onChangeModal({ type: 'setDriverIsShow', val: false });
                }}
              >

                <Text style={{ fontSize: px2dp(32), color: fontColorSecDeepGray }}>
                  取消
                </Text>
              </TouchableOpacity>
              <Text
                style={{
                  fontSize: px2dp(32),
                  color: fontColorBlack,
                  fontWeight: 'bold',
                }}
              >
                设置司机
              </Text>
              {!isShowInput ?
                <Submit
                  text='确定'
                  boxStyle={{
                    width: px2dp(104),
                    height: px2dp(60),
                    borderRadius: px2dp(8),
                    position: 'absolute',
                    right: px2dp(28),
                  }}
                  disabled={false}
                  onClick={() => {
                    this.toSetDriver('提交');
                  }}
                />
                :
                null}
            </View>
            {/* 填写司机手机号码 */}
            <ScrollView
              style={styles.editContainer}
              showsVerticalScrollIndicator={false}
            >
              {isShowInput
                ?
                listData.map((item, index) => (
                  <View style={index == 0 ? [styles.setDriver, { marginBottom: px2dp(40), marginTop: px2dp(39) }] : styles.setDriver}>
                    <View style={styles.flex}>
                      <Image style={styles.driverImg} source={item.url} />
                      <View>
                        <Text style={styles.diverTextTitle}>{item.title}</Text>
                        <Text style={styles.diverText}>{item.text}</Text>
                      </View>
                    </View>
                    <TouchableOpacity
                      activeOpacity={0.8}
                      onPress={() => {
                        this.toSetDriver(item.type);
                      }}
                    >
                      <LinearGradient
                        colors={['#686764', '#343332']}
                        style={[styles.toSet]}
                        start={{ x: 0, y: 0 }}
                        end={{ x: 1, y: 1 }}
                      >
                        <Text style={{ color: '#E3B25E', fontSize: px2dp(28) }}>设置</Text>
                        {/* <Image style={styles.driverRightImg} source={require('../../../../../image/wl/icon_right.png')} /> */}
                      </LinearGradient>
                    </TouchableOpacity>
                  </View>
                ))
                :
                <View style={styles.setOtherDriverInput}>
                  <Text style={{ color: '#343332', fontSize: px2dp(28) }}>司机</Text>
                  <TextInput
                    style={[
                      styles.driverInputText,
                    ]}
                    placeholder='请输入司机手机号码'
                    placeholderTextColor='#CDCCC9'
                    multiline={false}
                    maxLength={100}
                    defaultValue=''
                    value={driverPhone}
                    underlineColorAndroid='transparent'
                    keyboardType='numeric'
                    maxLength={11}
                    onChangeText={(text) => {
                      const newText = text.replace(/[^\d]+/, '');
                      this.setState({ driverPhone: newText });
                    }}
                    onBlur={() => {
                    }}
                  />
                </View>}

            </ScrollView>
          </View>
        </Modal>
      </SafeAreaView>
    );
  }

  // 查看合同
  checkContract = () => {
    const { carDetails } = this.state;
    msg.emit('router: goToNext', {
      routeName: 'ContractDetail',
      routerFrom: 'ownerCarDetail',
      contractId: carDetails.contractId,
      contractStatus: 4 // 查看合同
    });
  }

  submitDriver = (type, driver) => {
    const { carDetails } = this.state;
    if (type == '主') {
      if (driver) {
        // 更换主司机
        msg.emit('router: goToNext', {
          routeName: 'SetDriver',
          routerFrom: 'changeDriver',
          driverData: {
            type: 1,
            carId: carDetails && carDetails.id
          }
        });
      } else {
        // 设置主司机
        msg.emit('router: goToNext', {
          routeName: 'SetDriver',
          routerFrom: 'setDriver',
          driverData: {
            type: 1,
            carId: carDetails && carDetails.id
          }
        });
      }
    } else {
      if (driver) {
        // 更换副司机
        msg.emit('router: goToNext', {
          routeName: 'SetDriver',
          routerFrom: 'changeDriver',
          driverData: {
            type: 2,
            carId: carDetails && carDetails.id
          }
        });
      } else {
        // 设置副司机
        msg.emit('router: goToNext', {
          routeName: 'SetDriver',
          routerFrom: 'setDriver',
          driverData: {
            type: 2,
            carId: carDetails && carDetails.id
          }
        });
      }
    }
  }

  // 获取合同
  getCarContract = (carNo) => {
    contract.getCarContract({ carNo }).then(res => {
      if (res.success) {
        this.setState({ contractUrl: res.data });
      }
    });
  }

  // 跳转查看合同
  previewContract = () => {
    const { contractUrl } = this.state;
    msg.emit('router: goToNext', {
      routeName: 'previewContract',
      pdfUrl: contractUrl,
      contractState: false,
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
  },
  headers: {
    width: screenWidth,
    height: px2dp(108),
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderColor: splitLineColorLightGray,
  },
  header: {
    marginTop: px2dp(12) * 2,
    backgroundColor: '#fff',
    width: '100%',
    height: px2dp(92) * 2,
    flexDirection: 'row',
    alignItems: 'center'
  },
  fontSize16: {
    fontSize: px2dp(16) * 2,
    color: '#343332'
  },
  fontSize12: {
    fontSize: px2dp(12) * 2,
    color: '#999896'
  },
  fontSize14: {
    fontSize: px2dp(14) * 2,
    color: '#343332'
  },
  fontSizeGray14: {
    fontSize: px2dp(14) * 2,
    color: '#686764'
  },
  headImg: {
    width: px2dp(60) * 2,
    height: px2dp(60) * 2,
    borderRadius: px2dp(8) * 2
  },
  headLeft: {
    width: px2dp(60) * 2,
    height: px2dp(60) * 2,
    marginLeft: px2dp(16) * 2
  },
  headRight: {
    marginLeft: px2dp(12) * 2,
    flexDirection: 'column',
    justifyContent: 'space-between',
    height: px2dp(60) * 2,
  },
  setction: {
    backgroundColor: '#fff',
  },
  mr32: {
    marginRight: px2dp(32) * 2,
  },
  items: {
    backgroundColor: '#fff',
    flexDirection: 'row',
    alignItems: 'center',
    height: px2dp(52) * 2,
  },
  box: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: '100%',
    alignItems: 'center',
    marginLeft: px2dp(16) * 2
  },
  border: {
    borderBottomWidth: px2dp(1) * 2,
    borderColor: splitLineColorLightGray
  },
  footer: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center'
  },
  mask: {
    width: screenWidth,
    height: screenHeight,
    backgroundColor: 'rgba(0,0,0,0.2)',
    position: 'absolute',
    left: 0,
    top: 0,
  },
  cancel: {
    position: 'absolute',
    left: 0,
    top: 0,
    width: 80,
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  editContainer: {
    paddingHorizontal: px2dp(40),
    paddingBottom: px2dp(100),
  },
  infoContainer: {
    width: screenWidth,
    maxHeight: 0.5 * screenHeight,
    backgroundColor: mainBgColorWhite,
    position: 'absolute',
    bottom: 0,
    left: 0,
    borderRadius: px2dp(12),
    overflow: 'hidden',
    zIndex: 10,
  },
  setDriver: {
    height: px2dp(80) * 2,
    backgroundColor: '#F5F5F5',
    borderRadius: px2dp(16),
    width: '100%',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingLeft: px2dp(32),
    paddingRight: px2dp(40),
  },
  driverImg: {
    width: px2dp(44) * 2,
    height: px2dp(44) * 2,
    marginRight: px2dp(24)
  },
  diverTextTitle: {
    color: '#333232',
    fontSize: px2dp(32),
    fontWeight: 'bold'
  },
  diverText: {
    color: '#999896',
    fontSize: px2dp(26),
  },
  flex: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  toSet: {
    width: px2dp(136),
    height: px2dp(58),
    borderRadius: px2dp(29),
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center'
  },
  driverRightImg: {
    width: px2dp(12) * 2,
    height: px2dp(12) * 2,
  },
  setOtherDriverInput: {
    flexDirection: 'row',
    width: '100%',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginTop: px2dp(48),
    marginBottom: px2dp(80)
  },
  driverInputText: {
    height: px2dp(44) * 2,
    backgroundColor: '#F5F5F5',
    width: px2dp(300) * 2
  },
  emptyContent: {
    justifyContent: 'center',
    width: '100%'
  },
  carEmptyImg: {
    height: px2dp(240),
    marginTop: px2dp(120),
    marginBottom: px2dp(48)
  },
  emptyBoldText: {
    textAlign: 'center',
    marginBottom: px2dp(16),
    color: '#343332',
    fontSize: px2dp(34),
    fontWeight: 'bold'
  },
  emptyText: {
    textAlign: 'center',
    marginBottom: px2dp(56),
    paddingLeft: px2dp(75),
    paddingRight: px2dp(75),
    color: '#999796',
    fontSize: px2dp(28)
  },
  emptyBtn: {
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'center'
  },
  byContainer: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  byBox: {
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: px2dp(12),
    paddingVertical: px2dp(6),
    backgroundColor: '#F5F5F5',
    borderRadius: px2dp(8)
  },
  byText: {
    fontSize: px2dp(24),
    color: '#999896'
  },

  innerBox: {
    backgroundColor: '#fff',
    width: '100%',
    marginTop: px2dp(24)
  }
});
